#!/bin/bash
# 检查是否有设备连接
#
devices=$(adb devices | grep -w "device" | awk '{print $1}')

if [ -z "$devices" ]; then
  echo "No devices connected. Please connect a device and try again."
  exit 1
fi

# openssl x509 -inform PEM -in yourfile.pem -outform DER -out yourfile.cer

# 遍历当前目录下所有.cer文件
for cer_file in *.cer; do
  if [ -e "$cer_file" ]; then
    # 提取subject_hash_old
    output=$(openssl x509 -inform DER -subject_hash_old -in "$cer_file")
    subject_hash=$(echo "$output" | head -n 1)

    # 重命名文件
    new_filename="${subject_hash}.0"
    cp "$cer_file" "$new_filename"

    # 使用adb将文件推送到设备的/data/local/tmp目录
    adb push "$new_filename" /data/local/tmp

    # 创建移动证书的脚本内容
    read -r -d '' move_cert_script << EOF
#!/bin/bash
# 检查并删除现有的临时目录

if [ -d "/data/local/tmp/htk-ca-copy" ]; then
  rm -rf /data/local/tmp/htk-ca-copy
fi


# 开始移动证书
set -e # Fail on error
mkdir -m 700 /data/local/tmp/htk-ca-copy
cp /system/etc/security/cacerts/* /data/local/tmp/htk-ca-copy/
mount -t tmpfs tmpfs /system/etc/security/cacerts
mv /data/local/tmp/htk-ca-copy/* /system/etc/security/cacerts/
cp /data/local/tmp/${new_filename} /system/etc/security/cacerts/


chown root:root /system/etc/security/cacerts/*
chmod 644 /system/etc/security/cacerts/*
chcon u:object_r:system_file:s0 /system/etc/security/cacerts/*

rm -r /data/local/tmp/htk-ca-copy
echo "System cert successfully injected"
EOF
      # 将移动证书的脚本内容保存到文件
      echo "$move_cert_script" > moveCharlesCert.sh
      chmod +x moveCharlesCert.sh
      # 将moveCharlesCert.sh脚本推送到设备
      adb push moveCharlesCert.sh /data/local/tmp

      # 在设备上以root权限执行moveCharlesCert.sh脚本
      adb shell su -c "sh /data/local/tmp/moveCharlesCert.sh"

      # 在设备上执行完毕后，删除moveCharlesCert.sh脚本
      adb shell rm /data/local/tmp/moveCharlesCert.sh

      # 删除本地生成的.sh文件
      rm moveCharlesCert.sh

  else
    echo "No .cer files found in the current directory."
  fi
done

